import re
from rest_framework import serializers
from Login.models import user, Code
import datetime
from Login.utils import encrpty
from Login.service.login import makeCodeBeInvalid


# 注册序列化校验
class RegisterSerializer(serializers.ModelSerializer):
    verify_password = serializers.CharField(max_length=64)
    code = serializers.CharField(max_length=32)

    class Meta:
        model = user
        fields = ['username', 'password', 'verify_password', 'phone', 'email', 'code']
        read_only_fields = ('verify_password', 'code')

    def validate_password(self, data):
        # print(data)
        if not data:
            raise serializers.ValidationError('请输入密码')
        return encrpty.md5(data)

    def validate_verify_password(self, data):
        if not data:
            raise serializers.ValidationError("请确定密码")
        return encrpty.md5(data)

    def validate_code(self, data):
        # print("-*" * 50)
        # print(self.initial_data)
        email = self.initial_data.get("email")
        if not data:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        # print(code_verify,"---------------")

        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if data != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return data

    def validate_phone(self, data):
        if not data:
            raise serializers.ValidationError("请输入手机号")
        pattern = re.compile(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$')
        if not re.match(pattern, data):
            raise serializers.ValidationError("该手机号码格式错误，请确定格式正确后重新输入")
        if user.objects.filter(phone=data).exists():
            raise serializers.ValidationError("该手机号已被注册")
        return data

    def validate_email(self, data):
        if not data:
            raise serializers.ValidationError('请输入邮箱账号')
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not re.match(pattern, data):
            raise serializers.ValidationError("该邮箱格式错误，请确定格式正常后重新输入")
        if user.objects.filter(email=data).exists():
            raise serializers.ValidationError('该邮箱已被注册')
        return data


# 重置密码序列化校验（登录后）
class alter_passwordSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=32)
    password_confirm = serializers.CharField(max_length=64)

    class Meta:
        model = user
        fields = ['code', 'password', 'password_confirm']
        read_only_fields = ('code', 'password_confirm')

    def validate_code(self, data):
        email = self.initial_data.get("email")
        if not data:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if data != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return data

    def validate_password(self, data):
        if not data:
            raise serializers.ValidationError("请输入密码")
        return encrpty.md5(data)

    def validate_password_confirm(self, data):
        if not data:
            raise serializers.ValidationError("请确定密码")
        password = self.initial_data.get("password")
        if password != data:
            raise serializers.ValidationError("两次密码输入不一致，请重新输入")
        return encrpty.md5(data)


# 修改个人信息序列化校验
class alterInformationSerializer(serializers.ModelSerializer):
    substrings = ['tmd', 'fuck', '傻逼']  # 存放敏感词
    # 覆盖原字段，使其可以单独填写
    username = serializers.CharField(required=False, max_length=50)
    gender = serializers.CharField(required=False, max_length=6)
    # phone = serializers.CharField(required=False, max_length=15)
    code = serializers.CharField(required=False, max_length=32)

    class Meta:
        model = user
        fields = ['username', 'birthday', 'gender', 'province', 'city', 'country', 'introduce', 'code', 'email']

    def validate_email(self, value):
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not re.match(pattern, value):
            raise serializers.ValidationError("该邮箱格式错误，请确定格式正常后重新输入")
        if user.objects.filter(email=value).exists():
            raise serializers.ValidationError('该邮箱已被注册')
        return value
    #
    # def validate_phone(self, value):
    #     pattern = re.compile(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$')
    #     if not re.match(pattern, value):
    #         raise serializers.ValidationError("该手机号码格式错误，请确定格式正确后重新输入")
    #     if user.objects.filter(phone=value).exists():
    #         raise serializers.ValidationError("该手机号已被注册")
    #     return value

    def validate_introduce(self, value):
        if len(value) > 50:
            raise serializers.ValidationError("输入不能大于50字")
        for substring in self.substrings:
            if substring in value:
                raise serializers.ValidationError(f"请对简介进行修改，不要使用敏感词:{substring}！！！")
        return value

    def validate_code(self, value):
        email = self.initial_data.get("email")
        if not value:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if value != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return value


class UserSerializer(serializers.ModelSerializer):
    password_confirm = serializers.CharField(max_length=64)
    code = serializers.CharField(max_length=32)

    class Meta:
        model = user
        fields = ['email', 'password', 'password_confirm', 'code']

    def validate_email(self, value):
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not re.match(pattern, value):
            raise serializers.ValidationError("该邮箱格式错误，请确定格式正常后重新输入")
        return value

    def validate_code(self, data):
        email = self.initial_data.get("email")
        if not data:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if data != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return data

    def validate_password(self, data):
        if not data:
            raise serializers.ValidationError("请输入密码")
        return encrpty.md5(data)

    def validate_password_confirm(self, data):
        if not data:
            raise serializers.ValidationError("请确定密码")
        password = self.initial_data.get("password")
        if password != data:
            raise serializers.ValidationError("两次密码输入不一致，请重新输入")
        return encrpty.md5(data)


# 更改头像
class changeAvatarSerializer(serializers.ModelSerializer):

    class Meta:
        model = user
        fields = ['avatar']


